package hotgammon.view.tools;

import minidraw.framework.Tool;
import hotgammon.domain.*;
import hotgammon.view.*;
import hotgammon.view.figures.*;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;

public class GameStateTool implements Tool {
    
    private BackgammonUserInterface ui;
    private Tool checkerMoveTool;
    private Tool winnerTool;
    
    /** Creates a new instance of GameStateTool */
    public GameStateTool(BackgammonUserInterface ui) {
        this.ui = ui;
        this.checkerMoveTool = new CheckerMoveTool(this.ui);
        this.winnerTool = new WinnerTool(this.ui);
        
        printNewGame();
    }
    
    /**
     * Activates the tool for the given view. This method is called
     * whenever the user switches to this tool. Use this method to
     * reinitialize a tool.
     */
    public void activate() {
        
    }
    
    /**
     * Deactivates the tool. This method is called whenever the user
     * switches to another tool. Use this method to do some clean-up
     * when the tool is switched. Subclassers should always call
     * super.deactivate.
     */
    public void deactivate() {
        
    }
    
    /**
     * Handles mouse down events in the drawing view.
     */
    public void mouseDown(MouseEvent e, int x, int y) {
        if(hasWinner()) {
            winnerTool.mouseDown(e, x, y);
        } else {
            checkerMoveTool.mouseDown(e, x, y);
        }
    }
    
    /**
     * Handles mouse drag events in the drawing view.
     */
    public void mouseDrag(MouseEvent e, int x, int y) {
        if(hasWinner()) {
            winnerTool.mouseDrag(e, x, y);
        } else {
            checkerMoveTool.mouseDrag(e, x, y);
        }
    }
    
    /**
     * Handles mouse up in the drawing view.
     */
    public void mouseUp(MouseEvent e, int x, int y) {
        if(hasWinner()) {
            winnerTool.mouseUp(e, x, y);
        } else {
            checkerMoveTool.mouseUp(e, x, y);
        }
    }
    
    /**
     * Handles mouse moves (if the mouse button is up).
     */
    public void mouseMove(MouseEvent e, int x, int y) {
        if(hasWinner()) {
            winnerTool.mouseMove(e, x, y);
        } else {
            checkerMoveTool.mouseMove(e, x, y);
        }
    }
    
    /**
     * Handles key down events in the drawing view.
     */
    public void keyDown(KeyEvent evt, int key) {
        if(hasWinner() && key == 78 ) {
            ui.getGame().newGame();
            printNewGame();
        }
    }
    
    public boolean hasWinner() {
        if (ui.getGame().winner()!=Color.NONE) return true;
        return false;
    }
    
    private void printNewGame() {
        ui.getEditor().showStatus("New game started. "+ui.getGame().getPlayerInTurn()+" player in turn.");
    }
    
}
